package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.mapper.ReservationMemberMapper;
import com.zzyl.nursing.service.IReservationMemberService;
import com.zzyl.nursing.dto.ReservationMemberAddDto;
import com.zzyl.nursing.vo.CountByTimeVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.DateUtils;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 预约信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-28
 */
@Service
public class ReservationMemberMemberServiceImpl extends ServiceImpl<ReservationMemberMapper, Reservation> implements IReservationMemberService
{
    @Autowired
    private ReservationMemberMapper reservationMemberMapper;

    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return reservationMemberMapper.selectReservationById(id);
    }

    /**
     * 查询预约登记列表
     *
     * @param reservation 预约登记
     * @return 预约登记集合
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMemberMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     * 
     * @param dto 预约信息
     * @return 结果
     */
    @Override
    public AjaxResult insertReservation(ReservationMemberAddDto dto)
    {
        // 检查是否已存在相同时间段的预约
        Reservation queryReservation = new Reservation();
        queryReservation.setMobile(dto.getMobile());
        List<Reservation> reservations = reservationMemberMapper.selectReservationList(queryReservation);
        if (reservations != null && !reservations.isEmpty()) {
            return AjaxResult.error("该时间段已存在预约");
        }
        Long currentUserId = UserThreadLocal.get();
        dto.setStatus(0);
        dto.setCreateTime(LocalDateTime.now());
        dto.setUpdateTime(LocalDateTime.now());
        dto.setUpdateBy(currentUserId);
        dto.setCreateBy(currentUserId);
        reservationMemberMapper.insertReservation(dto);
        return AjaxResult.success();
    }

    /**
     * 修改预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        return reservationMemberMapper.updateReservation(reservation);
    }

    /**
     * 取消预约
     * @param id 预约ID
     * @return 结果
     */
    @Override
    public AjaxResult cancelReservation(Long id) {
        // 获取当前登录用户ID
        Long currentUserId = UserThreadLocal.get();
        Reservation reservation = getById(id);
        if (currentUserId == null) {
            return AjaxResult.error("用户未登录");
        } else if(ObjectUtil.isEmpty(reservation)){
            throw new BaseException("预约不存在");
        }// 查询该用户当前取消的预约次数
        int count = reservationMemberMapper.cancelledCount(currentUserId);

        // 判断次数是否超过限制（3次）
        if (count >= 3) {
            return AjaxResult.error("取消预约次数已达上限（3次）");
        }
        reservationMemberMapper.cancel(id);
        return AjaxResult.success();
    }

    /**
     * 根据用户ID获取当天取消预约次数
     *
     * @return 取消预约次数
     */
    @Override
    public AjaxResult getCancelledCountByUserId() {
        // 获取当前登录用户ID
        Long currentUserId = UserThreadLocal.get();
        if (currentUserId == null) {
            return AjaxResult.error("用户未登录");
        }

        // 查询该用户取消的预约次数
        int count = reservationMemberMapper.cancelledCount(currentUserId);
        return AjaxResult.success(count);
    }

    /**
     *
     * 查询每个时间段预约数量
     * @param
     * @return
     */
    @Override
    public List<CountByTimeVo> countReservationsForTime(Long time) {

        //2024-09-21
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        //2024-09-21 00:00:00
        LocalDateTime startTime = localDateTime.toLocalDate().atStartOfDay();
        //2024-09-22 00:00:00
        LocalDateTime endTime = startTime.plusHours(24);
        List<CountByTimeVo> timeCountVoList = reservationMemberMapper.countReservationsForTime(startTime,endTime);
        return timeCountVoList;
    }

    /**
     * 检查并更新过期预约状态
     */
    @Override
    public void checkAndUpdateExpiredReservations() {
        // 查询所有状态为0(待确认)的预约
        Reservation query = new Reservation();
        query.setStatus(0);
        List<Reservation> reservations = reservationMemberMapper.selectReservationList(query);
        
        // 遍历并检查是否过期
        for (Reservation reservation : reservations) {
            // 如果预约时间已过期，则更新状态为3(已过期)
            if (reservation.getTime().before(DateUtils.getNowDate())) {
                reservation.setStatus(3);
                reservationMemberMapper.updateReservation(reservation);
            }
        }
    }

    /**
     * 批量更新过期预约状态
     * @param expiredIds 过期预约ID列表
     */
    private void updateExpiredReservationsBatch(List<Long> expiredIds) {
        // 通过BaseMapper获取数据库连接，执行批量更新
        Reservation updateReservation = new Reservation();
        updateReservation.setStatus(3);
        updateReservation.setUpdateTime(new Date());

        // 构造更新条件
        for (Long id : expiredIds) {
            updateReservation.setId(id);
            reservationMemberMapper.updateReservation(updateReservation);
        }
    }


    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键集合
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return reservationMemberMapper.deleteReservationByIds(ids);
    }

    /**
     * 删除预约信息信息
     *
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id)
    {
        return reservationMemberMapper.deleteReservationById(id);
    }
}